package org.pewpew.server.persistence;

import java.util.UUID;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

public class DAO {
	private static final Logger log = Logger.getLogger(DAO.class.getCanonicalName());
	
	public static String getKey(String id, String dataType) {
		//Key key = KeyFactory.createKey(DataSet.class.getSimpleName(), id + dataType);
		String key = id + dataType;
		return key;
	}

	public static String generateID() {
		return UUID.randomUUID().toString();
	}

	public static void deleteData(String id, String dataType) {
		String key = getKey(id, dataType);
	    PersistenceManager pm = PMF.get().getPersistenceManager();
	    Query query = pm.newQuery(DataSet.class);
	    query.setUnique(true);
	    query.setFilter("key == keyParam");
	    query.declareParameters("String keyParam");
	    
	    DataSet data = null;
	    try {
	    	data = (DataSet) query.execute(key);
	        if (data == null) {
	        	log.warning ("Trying to delete non-existent data: " + key);
	        }
	        else {
	        	pm.deletePersistent(data);
	        }
	    } 
	    finally {
	        pm.close();
	    }
	}

	public static void storeData(String id, String dataType, String data) {
		String key = getKey(id, dataType);
		PersistenceManager pm = PMF.get().getPersistenceManager();
		DataSet dataset = new DataSet(id, dataType, data);
		dataset.setKey(key);
		@SuppressWarnings("unused")
		DataSet result = pm.makePersistent(dataset);
		//System.out.println(result);
	}

	public static String getData(String id, String dataType) {
		String key = getKey(id, dataType);
	    PersistenceManager pm = PMF.get().getPersistenceManager();
	    Query query = pm.newQuery(DataSet.class);
	    query.setUnique(true);
	    query.setFilter("key == keyParam");
	    query.declareParameters("String keyParam");
	    
	    DataSet data = null;
	    try {
			//data = (DataSet) pm.getObjectById(DataSet.class, key);
	    	data = (DataSet) query.execute(key);
	    } 
	    finally {
	        pm.close();
	    }
	    
	    if (data == null) {
	    	log.warning ("Cannot find data for request: " + key);
	    	return null;
	    }
	    return data.getData();
	}
}
